package com.http;

import com.http.method.Request;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by mac_wk on 14-11-19.
 */
public class HttpFactory {
    public static HttpURLConnection createHttp(Request request) throws IOException {

        HttpURLConnection connection = null;
        switch (request.getMethod()) {
            case HttpUtil.GET:
                connection = openGetConnection(request, request.getmUrl());
                break;
            case HttpUtil.POST:
                connection = OpenPostConnection(request, request.getmUrl());
                break;
        }
        return connection;
    }

    private static HttpURLConnection OpenPostConnection(Request request, String url_str) throws IOException {
        URL url = new URL(url_str);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

        httpConnection.setDoOutput(true);
        // Read from the connection. Default is true.
        httpConnection.setDoInput(true);
        // Set the post method. Default is GET
        httpConnection.setRequestMethod("POST");
        httpConnection.setConnectTimeout(request.getTimeout());
        httpConnection.setInstanceFollowRedirects(true);
        setHeader(request,httpConnection);
        return httpConnection;
    }

    private static HttpURLConnection openGetConnection(Request request, String url_str) throws IOException {
        Map<String, String> params = request.params;
        if (params != null && params.size() > 0) {
            int index = url_str.lastIndexOf("/");
            int length_index = url_str.length() - 1;
            StringBuilder sb = new StringBuilder();
            if (index != length_index)
                sb.append("/");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8") + "&");
            }
        }
        URL url = new URL(url_str);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        setHeader(request,httpConnection);//设置头部
        httpConnection.setRequestMethod("GET");
        return httpConnection;
    }
    private static void setHeader(Request request,HttpURLConnection httpConnection)
    {
        Map<String, String> head = request.head;

        if (request.getRequestType()!=null&&!"".equals(request.getRequestType()))
            httpConnection.setRequestProperty("Content-Type",request.getRequestType());
        if (head != null && head.size() > 0)
        {
            for (Map.Entry<String, String> entry : head.entrySet())
            {
                httpConnection.setRequestProperty(entry.getKey(),entry.getValue());
            }
        }
    }
}
